<?php

namespace Yjius\openapi\weibo;

use Yjius\common\CurlHelper;

/**
 * 微博扫码授权
 * Class WeiBoOauth
 * @package Yjius\openapi\weibo
 * @date  2022/7/26 17:03
 */
class WeiBoOauth
{
    //应用参数
    private $wb_akey = null;
    private $wb_skey = null;
    private $redirect_uri = null;

    //最外层初始化时，YII_ENV 可以选择不同的应用
    public function __construct($config = [])
    {
        //裁入配置
        $this->wb_akey = $config['wb_akey'] ?: '';
        $this->wb_skey = $config['wb_skey'] ?: '';
        $this->redirect_uri = $config['redirect_uri'] ?: '';
        if (empty($this->wb_akey) || empty($this->wb_skey)||empty($this->redirect_uri)) {
            throw new \Exception("载入配置错误，请检查参数是否正确");
        }
        $vendor = __DIR__ . '/saetv2.ex.class.php';
        require_once($vendor);
    }

    /**
     * 第一步：返回code_url
     */
    public function getCodeUrl($state = '')
    {
        $o = new \SaeTOAuthV2($this->wb_akey, $this->wb_skey);
        $code_url = $o->getAuthorizeURL($this->redirect_uri, 'code', $state);
        return $code_url;
    }

    /**
     * 第二步：通过code获取access_token
     * @param string $keys
     * @return array
     */
    public function getAccessToken($code = '', $type = "")
    {
        $keys = [
            'code' => $code,
            'redirect_uri' => $this->redirect_uri
        ];
        $o = new \SaeTOAuthV2($this->wb_akey, $this->wb_skey);
        $token = $o->getAccessToken('code', $keys);
        return $token;
    }

    // 第三步获取用户信息
    public function getUserShowByUid($access_token, $uid)
    {
        $url = 'https://api.weibo.com/2/users/show.json?access_token=' . $access_token . '&uid=' . $uid;
        $res = CurlHelper::httpRequest($url);
        return json_decode($res, true);
    }

    //---------------------------------------------------------------

    // 获取用户发布的微博信息列表 -- ok
    public function getWblist($uid, $token = '', $since_id = 0)
    {
        $o = new \SaeTClientV2($this->wb_akey, $this->wb_skey, $token);
        $res = $o->user_timeline_by_id($uid, 1, 50, $since_id);
        return $res;
    }

    // 发布一条微博--使用分享接口，且需要安全域名
    public function updateWb($status, $pic = false, $token)
    {
        $o = new \SaeTClientV2($this->wb_akey, $this->wb_skey, $token);
        $res = $o->share($status, $pic);
        return $res;
    }

    // 发布一条文字微博--使用 清博大数据 商业接口
    public function createWb($status, $token)
    {
        $o = new \SaeTClientV2($this->wb_akey, $this->wb_skey, $token);
        $res = $o->update($status, 1);
        return $res;
    }

    // 发布一条图文微博--使用 清博大数据 商业接口
    public function uploadWb($status, $pic, $token)
    {
        $o = new \SaeTClientV2($this->wb_akey, $this->wb_skey, $token);
        $res = $o->upload($status, $pic);
        return $res;
    }

    // 根据ID获取单条微博信息内容 -- ok
    public function showWbById($token, $id)
    {
        $o = new \SaeTClientV2($this->wb_akey, $this->wb_skey, $token);
        $res = $o->show_status($id);
        return $res;
    }
}